package cn.gson.crm.controller.aftersale;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.ProductDao;
import cn.gson.crm.model.dao.RepairDao;
import cn.gson.crm.model.dao.RepairDetailDao;
import cn.gson.crm.model.dao.CustomerDao;
import cn.gson.crm.model.entity.Customer;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.entity.Product;
import cn.gson.crm.model.entity.Repair;
import cn.gson.crm.model.entity.RepairDetail;
import cn.gson.crm.model.mapper.CustomerMapper;

import cn.gson.crm.model.mapper.ProductMapper;
import cn.gson.crm.model.mapper.RepairMapper;
import cn.gson.crm.service.AfterSaleService;

/**
 * 售后controller 客户可以对有问题的商品进行维修，通过客服人员新建维修工单 工单状态分为待接单、维修中、维修完、回访中、已完成
 * 客服人员先接单并新建维修工单，此为待接单状态； 维修员工接单后进行维修，这个过程为维修中状态； 维修员工填写维修金额完成维修后，这个状态称为维修完状态；
 * 客服人员回电客户通知客户具体状态，称为回访中状态； 回访完成，工单完成并作废；
 * 
 * 
 * 特殊情景： 客户打电话取消维修工单，此时直接操作工单为已完成状态，并写好备注 若现在日期超过工单规定截止日期，工单直接变为已完成的状态
 * 
 * @author LJJ
 *
 */

@Controller
@RequestMapping("/")
public class AfterSaleController {
	@Autowired
	private RepairDao repairDao;

	@Autowired
	private CustomerMapper customerMapper;

	@Autowired
	private AfterSaleService aftersaleService;

	@Autowired
	private CustomerDao customerDao;

	@Autowired
	private ProductMapper productMapper;

	@Autowired
	private ProductDao productDao;


	@Autowired
	private RepairDetailDao repairdetailDao;
	
	@Autowired
	private RepairMapper repairMapper;	

	/**
	 * 详情展示
	 * 
	 * @param page
	 * @param rows
	 * @param name
	 * @return
	 */
	@GetMapping({ "/aftersale/data" })
	@ResponseBody
	public Map<String, Object> after(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "10") int rows, @PathVariable(required = false) String name) {
		PageRequest pr = new PageRequest(page - 1, rows, new Sort(Direction.DESC, "state"));
		Map<String, Object> data = new HashMap<>();
		Page<Repair> repairs = repairDao.getAll(pr);
		data.put("rows", repairs.getContent());
		data.put("total", repairs.getTotalElements());
		return data;
	}

	/**
	 * 搜索功能
	 * 
	 * @param page
	 * @param rows
	 * @param name
	 * @return
	 */
	@RequestMapping({"/aftersale/search/{name}","/aftersale/search/{name}/{value}"})
	@ResponseBody
	public Map<String, Object> search(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "10") int rows, @PathVariable(required = false) String name,
			@PathVariable(required = false) String value) {
		PageRequest pr = new PageRequest(page - 1, rows, new Sort(Direction.DESC, "state"));
		Map<String, Object> data = new HashMap<>();
		System.out.println(value);
		if (value==null) {
			if (name.equals("all")) {
				Page<Repair> repairs = repairDao.getAll(pr);
				data.put("rows", repairs.getContent());
				data.put("total", repairs.getTotalElements());
			} else {
				Page<Repair> searchRepairs = repairDao.findByProgress(name, pr);
				data.put("rows", searchRepairs.getContent());
				data.put("total", searchRepairs.getTotalElements());
			}
		} else {
			 Page<Repair> searchNum = repairDao.findByNumber(value,pr); 
			 data.put("rows", searchNum.getContent());
			 data.put("total", searchNum.getTotalElements());
		}
		return data;
	}

	@GetMapping("/aftersale/main")
	public String afterMain() {
		return "aftersale/aftersale";
	}

	/**
	 * 新增维修工单，get提交
	 * 
	 * @return
	 */
	@GetMapping({ "/aftersale/add" })
	public String add(Model model) {
		model.addAttribute("num", aftersaleService.createNum());
		Date date = new Date();
		model.addAttribute("createdate", date);
		model.addAttribute("enddate", aftersaleService.getResult());
		return "aftersale/add";
	}

	/**
	 * 
	 * @param repair
	 * @param detail
	 * @param cname
	 *            客户名称
	 * @param pname
	 *            产品名称
	 */
	@Transactional
	@ResponseBody
	@RequestMapping("/aftersale/save")
	public JSONObject save(@Valid Repair repair,HttpSession session, String cname, String ename, String bz, BindingResult br, Model model) {
		JSONObject result = new JSONObject();
		Employee employee = (Employee) session.getAttribute("employee");
		Customer customer = customerDao.findOneByName(cname);
		Product product = productDao.findOneByName(repair.getContent());
		repair.setCustomer(customer);
		repair.setProduct(product);
		repair.setEmployee(employee);
		if (repair.getProgress().equals("已完成")) {
			repair.setState(true);
		} else {
			// 维修单未完成
			repair.setState(false);
		}
		repairDao.save(repair);
		RepairDetail detail = new RepairDetail();
		// 明细表设置最新时间
		detail.setTime(repair.getDate());
		detail.setRepair(repair);
		detail.setProgress(repair.getProgress());
		if (br.hasErrors()) {
			result.put("err", "校验失败");
		}
		// 保存维修明细表
		detail.setContent(bz);
		// 保存对应的员工
		detail.setEmployee(employee);
		repairdetailDao.save(detail);
		System.out.println("维修单明细id" + detail.getId());
		result.put("success", "保存成功");
		return result;
	}

	@GetMapping("/aftersale/show/{id}")
	public String show(@PathVariable Long id, Model model) {
		Repair repair = repairDao.findOne(id);
		List<RepairDetail> details = repairdetailDao.findByRepair(repair);
		model.addAttribute("repair", repair);
		model.addAttribute("details", details);
		return "aftersale/show";
	}

	/**
	 * 高级查询
	 * 
	 * @return
	 */
	@GetMapping("/aftersale/highcheck")
	public String highCheck() {
		
		return "aftersale/highcheck";
	}
	
	/**
	 * 高级查询提交
	 */
	@PostMapping("/aftersale/highcheck/submit")
	@ResponseBody
	public  Map<String, Object> submit(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "10") int rows ,Repair repair,String cname,String pname){
		 Map<String, Object> map = new HashMap<>();
		repair.setCustomer(customerDao.findByName(cname));
		repair.setProduct(productDao.findOneByName(pname));
		map.put("number", repair.getNumber());
		if(repair.getDate()==null){
			map.put("date", repair.getDate());
		}else{
			map.put("date",aftersaleService.getDate(repair.getDate()));
		}
		if(repair.getCustomer()!=null){
			map.put("cname", repair.getCustomer().getName());
		}
		if(repair.getProduct()!=null){
			map.put("pname", repair.getProduct().getName());
		}
		map.put("tel", repair.getTel());
		List<Repair> repairs = repairMapper.getRepairsByHighcheck(map);
		PageHelper.startPage(page, rows,true);
		PageInfo<Repair> pageInfo = new PageInfo<Repair>(repairs);
		
		map.put("rows", pageInfo.getList());
		map.put("total", pageInfo.getPages());
		return map;
	}

	/**
	 * 编辑工具栏
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@GetMapping({ "/aftersale/edit", "/aftersale/edit/{id}" })
	public String edit(@PathVariable(required = false) Long id, Model model) {
		Repair repair = repairDao.findOne(id);
		Date date = new Date();
		model.addAttribute("editTime", date);
		model.addAttribute("repair", repair);
		return "aftersale/edit";
	}

	@GetMapping("/aftersale/delete")
	public String delete() {
		return "aftersale/delete";
	}

	/**
	 * 维修详情表格
	 * 
	 * @return
	 */
	@RequestMapping("/aftersale/detail/{id}")
	@ResponseBody
	public List<RepairDetail> repairDetail(@PathVariable Long id) {
		Repair repair = repairDao.findOne(id);
		List<RepairDetail> details = repairdetailDao.findByRepair(repair);
		return details;
	}

	/**
	 * 搜索对应客户
	 * 
	 * @param cname
	 * @param response
	 * @return
	 */
	@RequestMapping("/aftersale/findclient")
	@ResponseBody
	public List<Customer> getClient(@RequestParam String cname, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		List<Customer> customer = customerMapper.searchName(cname);
		return customer;
	}

	@RequestMapping("/aftersale/findproduct")
	@ResponseBody
	public List<Product> getProduct(@RequestParam String pname, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		System.out.println("enter");
		return productMapper.searchProduct(pname);
	}
	
	/**
	 * 导出数据到excel
	 */
	@RequestMapping("/aftersale/export")
	public void export(HttpServletRequest req,HttpServletResponse resp){
		List<Repair> repairs = repairDao.selectRepairs();
		HSSFWorkbook workbook = aftersaleService.createExcel(repairs, req);
		 SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 定义文件名格式 
		 try {
			String msg = new String( 
			          ("客户信息_" + format.format(new Date()) + ".xls").getBytes(), 
			          "ISO-8859-1");
			resp.setContentType("application/vnd.ms-excel");
			resp.addHeader("Content-Disposition", "attachment;filename="+ msg);
				workbook.write(resp.getOutputStream());
				}
			 catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	

	@RequestMapping("/weixiu")
	public void weixiu() {
		
	}

}
